define(['jquery'], function ($) {
    new commentAction().init();
    new comment().init();
});
var commentAction = function detail() {
    this.init = function () {
        console.log($('.face-motion'));
        for(let i=0;i<$('.face-motion').length;i++){
            var _self = $('.face-motion')[i];
            $(_self).SinaEmotion($('.'+$(_self).attr('attr')));
        }
    }
}
var comment = function () {
    var coment_btn ='.plBtn';
    var target = this;
    var edit ='.atrEdit';
    var form ={
        nick_name:'',
        website:'',
        content:'',
        article_id:0,
        target_id:0,
        type:0
    };
    var cpmmentPage = { /*评论*/
        page: 1,
        pageSize: 10,
        total: 0
    };
    var subPage = { /*查看评论*/
        page: 1,
        pageSize: 10,
        total: 0
    };
    var moreClick = {
        'reply': $('.loadmore'),
    };
    var commentContent = '.contentInner';
    var commentTemplate = '#commentTemplate';
    var subCommentTemplate = "#subCommentTemplate";
    this.init = function () {
        this.initClick();
        this.renderComment();
    }
    this.initClick = function () {
        /*发表对文章的评论*/
        $(coment_btn).click(function () {
            var alls =$('.comment-lsit').find('.atrEdit');
            target.publicComment(alls,commentContent,commentTemplate,0);
        });
        /*回复*/
        $('body').on('click', 'a.reply', function () {
            var clickElement = $('#' + $(this).attr('attr'));
            if ($(this).hasClass('checked')) {
                $(this).removeClass('checked');
                $(this).text('回复');
                $(clickElement).hide(700);
            } else {
                $(this).addClass('checked');
                $(this).text('收起回复');
                $(clickElement).show(700);
            }
            if (!!window.ActiveXObject || "ActiveXObject" in window)
            {
                $(clickElement).find('textarea').html('');
                $(clickElement).find('textarea').attr('placeholder', $(clickElement).find('textarea').attr('placeholder'));
            }
        });

        /*确认回复*/
        $('body').on('click', 'a.do-reply', function () {
            target.doReply($(this), 'reply_');
        });
        /*取消评论*/
        $('body').on('click', 'a.cancel-reply', function () {
            target.clearReply($(this), 'reply_');
        });
        /*产看评论*/
        /*查看评论绑定*/
        $('body').on('click', 'a.reback', function () {
            var total = $(this).attr('total');
            var content_id = $(this).attr('content_id');
            var clickElement = $('#' + $(this).attr('clickId'));
            subPage.page=1;
            if ($(this).hasClass('checked')) {
                $(this).removeClass('checked');
                $(this).text('查看评论');
                $(clickElement).hide(700);
            } else {
                $(this).addClass('checked');
                $(this).text('收起评论');
                $(clickElement).show(700);
                $(clickElement).find('ul').html('');
                target.getSubComment('append', content_id, clickElement);
            }
        });

    }
    /**
     *
     * @param alls
     * @param element
     * @param template
     * @param reply_id
     */
    this.publicComment = function (alls,element,template,reply_id) {
        var flag = false;
        var r = /\s+/g;
        for(var i=0;i<alls.length;i++){
            form[$(alls[i]).attr('name')] = $(alls[i]).val();
            if($(alls[i]).attr('name')=='content'||$(alls[i]).attr('name')=='nick_name'){
                var text = $(alls[i]).val().replace(r, " ");
                if (text=='') {
                    flag = true;
                    target.error($(alls[i]));
                }
            }
        }
        form['reply_id'] = reply_id
        if(!flag){
            target.replyUser(form,element,template);
        }
    }
    this.error = function (element) {
        $(element).addClass('error');
        $(element).focus(function(){
            $(element).removeClass('error');
        });

    }
    this.renderComment = function () {
        var promise = window.API.publicApi.getMessage(article_id);
        promise.then(function (result) {
            if (result.status ==1) {
                cpmmentPage.total = result.data.total;
                $('.total').find('span').find('i').text(cpmmentPage.total);
                target.buildHtml(result.data.rows, 'append',commentContent,commentTemplate);
                if( cpmmentPage.total<=cpmmentPage.pageSize){
                    $(moreClick.reply).hide();
                }
                if (result.data.rows.length < cpmmentPage.pageSize && cpmmentPage.pageSize * cpmmentPage.page > cpmmentPage.total) {
                    $(moreClick.reply).addClass('unableLoad');
                    $(moreClick.reply).find('a').text('加载完毕');
                }
                if(cpmmentPage.total<=0){
                    $('.comment-detail').hide();
                }
            }
        })
    }
    this.getSubComment = function (target_id) {
        var promise = window.API.publicApi.getSubcomment(target_id,article_id);
        promise.then(function (result) {
            if (result.status ==1) {
                subPage.total = result.data.total;
                $('.total').find('span').find('i').text(subPage.total);
                target.buildHtml(result.data.rows, 'append',commentContent,commentTemplate);
                if( subPage.total<=subPage.pageSize){
                    $(moreClick.reply).hide();
                }
                if (result.data.rows.length < subPage.pageSize && subPage.pageSize * subPage.page > subPage.total) {
                    $(moreClick.reply).addClass('unableLoad');
                    $(moreClick.reply).find('a').text('加载完毕');
                }
                if(subPage.total<=0){
                    $('.comment-detail').hide();
                }
            }
        })
    }
    /***
     * 回复文章
     * @param form
     * @param element
     * @param template
     * @param type
     */
    this.replyUser = function (form,element,template) {
        var promise = window.API.publicApi.comment(form);
        promise.then(function (result) {
            var data = {};
            if(result.status==1){
                var rows = [];
                rows.push(result.data);
                data['rows'] = rows;
                target.buildHtml(data.rows,'prepend',element,template);
                target.clear();

            }
        })
    }
    this.buildHtml = function (result, type, element, elementTemplate) {
        var target = this;
        var htmls = [];
        var templateHtml = $(elementTemplate).html();
        for (var rowsKey in result) {
            var row = result[rowsKey];
            row['index'] = rowsKey;
            var engine = new HtmlTemplateEngine();
            engine.setMapper(target.buildMapper(row));
            htmls.push(engine.buildText(templateHtml));
        }
        if (type == 'prepend') {
            $(element).prepend(htmls.join(''));
        } else {
            $(element).append(htmls.join(''));
        }
    };
    this.buildPublicMapper = function (row) {
        if(row.reply_id != row.target_id){
            row.nick_dialog = '<i>'+row.nick_name+'</i>回复<i>'+row.reply_name+'</i>';
        }else{
            row.nick_dialog = row.nick_name;
        }
        return  Object.assign({}, row);
    }
    this.buildMapper = function (row) {
        var target = Object.assign({}, row);
        if(target.reply_id != target.target_id){
            target.nick_dialog = '<i>'+target.nick_name+'</i>回复<i>'+target.reply_name+'</i>';
        }else{
            target.nick_dialog = target.nick_name;
        }
        target.html = this.getHtml(row['comment_content']);
        console.log(target);
        return  target;
    };
    this.getHtml = function (result) {
        var target = this;
        var htmls = [];
        for (var rowsKey in result) {
            var row = result[rowsKey];
            row['index'] = rowsKey;
            var engine = new HtmlTemplateEngine();
            engine.setMapper(target.buildPublicMapper(row));
            var templateHtml = $(subCommentTemplate).html();
            htmls.push(engine.buildText(templateHtml));
        }
        return htmls.join('');
    }
    this.clear = function () {
        var alls =$(edit);
        for(var i=0;i<alls.length;i++){
            $(alls[i]).val('');
        }
    }
    this.clearReply = function (element, type) {
        var elementId =$(element).attr('content_id');
        var value = $('#' + type + elementId).find('textarea');
        $(value).val('');
        $('#' + type + elementId).hide(700);
        $("a[attr='" + type + elementId + "']").removeClass('checked');
        $("a[attr='" + type + elementId + "']").siblings('.reback').attr('total', true);
        $("a[attr='" + type + elementId + "']").text('回复');
    };
    /***
     * 所有对留言的回复 清除回复
     * @param element
     * @param type
     */
    this.doReply = function (element, type) {
        var target = this;
        var elementId =$(element).attr('content_id');
        form.target_id = elementId;
        var alls =$('#'+type+elementId).find('.atrEdit');
        var reply_id = $(element).attr('reply_id');
        target.publicComment(alls,'.comment_'+reply_id,subCommentTemplate,reply_id);
    };
}